import cv2 
import torch
import os 
import uuid

def worker_process_video(video_path):
    #创建一个 output文件夹(如果不存在) 
    output_dir = "./output"
    os .makedirs(output_dir,exist_ok=True)

    #生成一个唯一的输出文件名
    output_filename= f"process_video_{uuid.uuid4().hex}.mp4" 
    output_path = os.path.join(output_dir,output_filename )

    #加载模型
    model = torch.hub.load('./yolov5','custom', path='./models/yolov5s.pt', source='local')
    

    #创建视频捕获对象
    cap=cv2.VideoCapture(video_path)

    #获取视频的属性
    frame_width=int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    frame_height=int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)

    fourcc=cv2.VideoWriter_fourcc(*'mp4v')
    out=cv2.VideoWriter(output_path,fourcc,fps,(frame_width,frame_height ))

    while cap.isOpened():
        ret,frame = cap.read() 
        if not ret:
            break
        #对每一帧进行目标检测
        results = model(frame)

        #渲染结果(在帧上绘制边界框等)
        rendered_frame = results.render()[0]

        #显示处理好的帧
        cv2.imshow('YOLOV5 Detection',rendered_frame)

        #保存处理后的帧到输出视频(可选) 
        out.write(rendered_frame)

        #按'q'退出程序
        if cv2.waitKey(1) & 0xFF ==ord('q'):
            break

    #释放资源
    cap.release() 
    out.release()
    cv2.destroyAllWindows()